import { defineStore } from "pinia";

export const userStore = defineStore("user", {
  state: () => ({
    id: localStorage.getItem("user-id") || null, // 从 localStorage 恢复数据
    isLoggedIn: !!localStorage.getItem("user-logged-in"), // 检查登录状态
    account: localStorage.getItem("user-account") || null,
    userName: localStorage.getItem("user-name") || null,
    token: localStorage.getItem("token") || null,
    className: localStorage.getItem("className") || null,
  }),
  actions: {
    login(newId, account, userName, token, className) {
      this.id = newId;
      this.isLoggedIn = true;
      this.account = account;
      this.userName = userName;
      this.token = token;
      this.className = className;
      // 将数据保存到 localStorage
      localStorage.setItem("user-id", newId);
      localStorage.setItem("user-logged-in", "true");
      localStorage.setItem("user-account", account);
      localStorage.setItem("user-name", userName);
      localStorage.setItem("token", token);
      localStorage.setItem("className", className);
      //localStorage.setItem("token", typeof token === 'string' ? token : JSON.stringify(token));
    },
    logout() {
      this.id = null;
      this.isLoggedIn = false;

      // 清除 localStorage 中的数据
      localStorage.removeItem("user-id");
      localStorage.removeItem("user-logged-in");
      localStorage.removeItem("token");
      localStorage.removeItem("className");
    },
  },
});
